﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace ResourceTypeConfigurationApp
{
    public partial class fmNewObjectDevice : Form
    {
        // 新增：资源对象参数类
        public class ResourceObjectInfo
        {
            public string Id { get; set; }
            public string FactoryStationId { get; set; }
            public string Name { get; set; }
            public string CustomNo { get; set; }
            public string ResourceTypeId { get; set; }
            public string ParentFactoryStationId { get; set; }
            public int RangeType { get; set; }
            public int IsDel { get; set; }
            public string PushType { get; set; }
            public string PtDate { get; set; }
            public string WhDate { get; set; }

            public DataTable dtPushType { get; set; }
            public DataTable dtResourceType { get; set; }
        }

        // 新增：用于传递资源对象参数
        public ResourceObjectInfo ResourceObjectParams { get; set; }
        public fmNewObjectDevice()
        {
            InitializeComponent();
        }

        private async void fmNewObjectDevice_Load(object sender, EventArgs e)
        {
            // 只显示参数，不可编辑
            if (ResourceObjectParams != null)
            {
                this.cbxPushType.ValueMember = "VALUE";
                this.cbxPushType.DisplayMember = "TEXT";
                this.cbxResourceType.ValueMember = "VALUE";
                this.cbxResourceType.DisplayMember = "TEXT";
                cbxPushType.DataSource = ResourceObjectParams.dtPushType;
                cbxResourceType.DataSource = ResourceObjectParams.dtResourceType;
                txtName.Text = ResourceObjectParams.Name;
                txtCustomNo.Text = ResourceObjectParams.CustomNo;
                txtCustomNo.ReadOnly = true;
                txtParentID.Text = ResourceObjectParams.ParentFactoryStationId;
                txtParentID.ReadOnly = true;
                txtPtDate.Text = ResourceObjectParams.PtDate;
                txtPtDate.ReadOnly = true;
                txtWhDate.Text = ResourceObjectParams.WhDate;
                txtWhDate.ReadOnly = true;
                cbOn.Checked = ResourceObjectParams.IsDel == 0;
                cbOn.Enabled = false;
                if (!string.IsNullOrEmpty(ResourceObjectParams.ResourceTypeId))
                {
                    cbxResourceType.SelectedValue = ResourceObjectParams.ResourceTypeId;
                }
                cbxResourceType.Enabled = false;
                if (!string.IsNullOrEmpty(ResourceObjectParams.PushType))
                {
                    cbxPushType.SelectedValue = ResourceObjectParams.PushType;
                }
                cbxPushType.Enabled = false;
                //加载可选择设备和已选择设备
                {
                    var dtA = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.soureConnectionString, $@"SELECT ID,CLASSNAME,`NAME`,PATHID from dev_powersystemresource where PATHID like '%\\\\{ResourceObjectParams.FactoryStationId}%' AND CLASSNAME = 'Bay' order by PATHID;");
                    if (dtA.Rows.Count == 0)
                    {
                        MessageBox.Show("没有查询到相关数据");
                        return;
                    }
                    if (!dgDevice.Columns.Contains("IsSelected"))
                    {
                        // 创建一个DataGridViewCheckBoxColumn
                        DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
                        checkBoxColumn.HeaderText = "选中";
                        checkBoxColumn.Name = "IsSelected";
                        checkBoxColumn.DataPropertyName = "IsSelected";
                        // 将勾选列添加到DataGridView
                        dgDevice.Columns.Add(checkBoxColumn);
                    }

                    // 为DataTable添加对应的列
                    dtA.Columns.Add("IsSelected", typeof(bool));
                    dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

                    DeviceBindingSource.DataSource = dtA;
                    dgDevice.DataSource = DeviceBindingSource;

                    dgDevice.Columns["ID"].HeaderText = "ID";
                    dgDevice.Columns["CLASSNAME"].HeaderText = "类型";
                    dgDevice.Columns["NAME"].HeaderText = "名称";
                    dgDevice.Columns["PATHID"].HeaderText = "路径";
                    dgDevice.AutoResizeColumns();
                    lbCount.Text = dtA.Rows.Count.ToString();

                    // 设置不允许新增行
                    dgDevice.AllowUserToAddRows = false;

                    dgDevice.AllowUserToDeleteRows = false; // 禁止删除行

                    dgDevice.ContextMenuStrip = contextMenuStrip1;
                }
                if (!string.IsNullOrWhiteSpace(ResourceObjectParams.Id))
                {
                    var dtRA = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT device_key,binding_time,delete_time,deleted FROM custom_resource_object_device WHERE custom_resource_object_device.custom_resource_object_id ='{ResourceObjectParams.Id}' ORDER BY custom_resource_object_device.binding_time;");

                    RDeviceBindingSource.DataSource = dtRA;
                    dgRDevice.DataSource = RDeviceBindingSource;

                    dgRDevice.Columns["device_key"].HeaderText = "ID";
                    dgRDevice.Columns["binding_time"].HeaderText = "绑定时间";
                    dgRDevice.Columns["delete_time"].HeaderText = "删除时间";
                    dgRDevice.Columns["deleted"].HeaderText = "是否删除";
                    dgRDevice.AutoResizeColumns();
                    lbRDeviceCount.Text = dtRA.Rows.Count.ToString();

                    // 设置不允许新增行
                    dgRDevice.AllowUserToAddRows = false;

                    dgRDevice.AllowUserToDeleteRows = false; // 禁止删除行

                }
            }



        }





        private async void btnNew_Click(object sender, EventArgs e)
        {
            if (ResourceObjectParams == null)
            {
                MessageBox.Show("传入数据错误");
                return;
            }
            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA == null || !dtA.AsEnumerable().Any(x => x["IsSelected"].ToString() == "True"))
            {
                MessageBox.Show("请先勾选数据");
                return;
            }

            if (string.IsNullOrWhiteSpace(txtBindDate.Text))
            {
                MessageBox.Show("绑定时间不可为空！");
                return;
            }
            string format = "yyyyMMdd";
            if (!DateTime.TryParseExact(txtBindDate.Text, format, null, System.Globalization.DateTimeStyles.None, out DateTime BindDate))
            {
                MessageBox.Show("绑定时间的时间格式错误！");
                return;
            }

            if (!DateTime.TryParseExact(txtPtDate.Text, format, null, System.Globalization.DateTimeStyles.None, out DateTime PtDate))
            {
                MessageBox.Show("功率更新时间的时间格式错误！");
                return;
            }
            if (!DateTime.TryParseExact(txtWhDate.Text, format, null, System.Globalization.DateTimeStyles.None, out DateTime WhDate))
            {
                MessageBox.Show("电量更新时间的时间格式错误！");
                return;
            }

            var drs = dtA.AsEnumerable().Where(x => x["IsSelected"].ToString() == "True");
            var ids = drs.Select(x => x["ID"].ToString()).ToList();

            // 判断资源对象是否存在
            if (string.IsNullOrWhiteSpace(ResourceObjectParams.Id))
            {
                // 通过 factory_station_id + resource_type_id 判断
                var dtResourceObject = await MySQLHelper.GetDataTableBySqlAsync(
                    MySQLHelper.targetConnectionString,
                    $@"SELECT id FROM custom_resource_object WHERE factory_station_id={MySQLHelper.ConvertGuidToSql(ResourceObjectParams.FactoryStationId)} AND custom_resource_type_id={MySQLHelper.ConvertGuidToSql(ResourceObjectParams.ResourceTypeId)} AND custom_no {MySQLHelper.ConvertGuidToSelectSql(ResourceObjectParams.CustomNo)}"
                );
                if (dtResourceObject == null || dtResourceObject.Rows.Count == 0)
                {
                    // 不存在则新建资源对象
                    string insertSql = $@"insert into custom_resource_object(range_type,factory_station_id,fname,custom_no,custom_resource_type_id,parent_factory_station_id,create_time,update_time,deleted,push_type)VALUES ({ResourceObjectParams.RangeType},{MySQLHelper.ConvertGuidToSql(ResourceObjectParams.FactoryStationId)},{MySQLHelper.ConvertGuidToSql(ResourceObjectParams.Name)},{MySQLHelper.ConvertGuidToSql(ResourceObjectParams.CustomNo)},{MySQLHelper.ConvertGuidToSql(ResourceObjectParams.ResourceTypeId)},{MySQLHelper.ConvertGuidToSql(ResourceObjectParams.ParentFactoryStationId)},NOW(),NOW(),{ResourceObjectParams.IsDel},{MySQLHelper.ConvertGuidToSql(ResourceObjectParams.PushType)});SELECT id from custom_resource_object where factory_station_id={MySQLHelper.ConvertGuidToSql(ResourceObjectParams.FactoryStationId)} and custom_resource_type_id={MySQLHelper.ConvertGuidToSql(ResourceObjectParams.ResourceTypeId)}  AND custom_no {MySQLHelper.ConvertGuidToSelectSql(ResourceObjectParams.CustomNo)};";
                    var dtInsert = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, insertSql);
                    if (dtInsert == null || dtInsert.Rows.Count == 0)
                    {
                        MessageBox.Show("新建资源对象失败！");
                        return;
                    }
                    ResourceObjectParams.Id = dtInsert.Rows[0]["id"].ToString();
                    // 新建 custom_object_value_type_time
                    if (!string.IsNullOrEmpty(ResourceObjectParams.PtDate))
                    {
                        string sqlPt = $@"INSERT into custom_object_value_type_time(custom_resource_object_id,data_value_type,update_day)VALUES({ResourceObjectParams.Id},0,'{PtDate}')";
                        await MySQLHelper.ExecuteSqlAsync(MySQLHelper.targetConnectionString, new List<string> { sqlPt });
                    }
                    if (!string.IsNullOrEmpty(ResourceObjectParams.WhDate))
                    {
                        string sqlWh = $@"INSERT into custom_object_value_type_time(custom_resource_object_id,data_value_type,update_day)VALUES({ResourceObjectParams.Id},1,'{WhDate}')";
                        await MySQLHelper.ExecuteSqlAsync(MySQLHelper.targetConnectionString, new List<string> { sqlWh });
                    }
                }
                else
                {
                    ResourceObjectParams.Id = dtResourceObject.Rows[0]["id"].ToString();
                }
            }

            // 判断设备是否已关联资源对象
            var dtResourceObjectDevice = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id,device_key FROM custom_resource_object_device WHERE custom_resource_object_id={MySQLHelper.ConvertGuidToSql(ResourceObjectParams.Id)} and deleted = 0 and device_key IN ({MySQLHelper.ConvertListToStr(ids)})");
            if (dtResourceObjectDevice != null && dtResourceObjectDevice.Rows.Count > 0)
            {
                MessageBox.Show($@"已存在设备对象{string.Join(",", dtResourceObjectDevice.AsEnumerable().Select(x => x["device_key"].ToString()))}！");
                return;
            }

            List<string> sqlList = new List<string>();
            //插入数据
            foreach (var item in dtA.AsEnumerable().Where(x => x["IsSelected"].ToString() == "True"))
            {
                sqlList.Add($@"insert into custom_resource_object_device (custom_resource_object_id,device_key,binding_time,create_time,update_time)VALUES ({MySQLHelper.ConvertGuidToSql(ResourceObjectParams.Id)},{MySQLHelper.ConvertGuidToSql(item["ID"].ToString())},'{BindDate}',NOW(),NOW())");
            }

            if (await MySQLHelper.ExecuteSqlAsync(MySQLHelper.targetConnectionString, sqlList))
            {
                MessageBox.Show("新建资源对象设备成功");
                //刷新数据
                if (!string.IsNullOrWhiteSpace(ResourceObjectParams.Id))
                {
                    var dtRA = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT device_key,binding_time,delete_time,deleted FROM custom_resource_object_device WHERE custom_resource_object_device.custom_resource_object_id ='{ResourceObjectParams.Id}' ORDER BY custom_resource_object_device.binding_time;");

                    RDeviceBindingSource.DataSource = dtRA;
                    dgRDevice.DataSource = RDeviceBindingSource;

                    dgRDevice.Columns["device_key"].HeaderText = "ID";
                    dgRDevice.Columns["binding_time"].HeaderText = "绑定时间";
                    dgRDevice.Columns["delete_time"].HeaderText = "删除时间";
                    dgRDevice.Columns["deleted"].HeaderText = "是否删除";
                    dgRDevice.AutoResizeColumns();
                    lbRDeviceCount.Text = dtRA.Rows.Count.ToString();

                    // 设置不允许新增行
                    dgRDevice.AllowUserToAddRows = false;

                    dgRDevice.AllowUserToDeleteRows = false; // 禁止删除行
                }
            }
            else
            {
                MessageBox.Show("新建资源对象设备失败");
            }
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            //var dtA = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT custom_resource_object.id,custom_resource_object.factory_station_id,custom_resource_object.fname,custom_resource_type.type_name,custom_resource_object.parent_factory_station_id,custom_resource_object.custom_no FROM custom_resource_object LEFT JOIN custom_resource_type ON custom_resource_object.custom_resource_type_id = custom_resource_type.id WHERE custom_resource_object.fname LIKE '%{txtSiteName.Text}%' ORDER BY custom_resource_object.fname,custom_resource_type.range_type,custom_resource_type.id ");
            //if (dtA == null || dtA.Rows.Count == 0)
            //{
            //    MessageBox.Show("没有查询到相关数据");
            //    return;
            //}
            //if (!dgSite.Columns.Contains("IsSelected"))
            //{
            //    // 创建一个DataGridViewCheckBoxColumn
            //    DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            //    checkBoxColumn.HeaderText = "选中";
            //    checkBoxColumn.Name = "IsSelected";
            //    checkBoxColumn.DataPropertyName = "IsSelected";
            //    // 将勾选列添加到DataGridView
            //    dgSite.Columns.Add(checkBoxColumn);
            //}

            //// 为DataTable添加对应的列
            //dtA.Columns.Add("IsSelected", typeof(bool));
            //dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

            //// 设置不允许新增行
            //dgSite.AllowUserToAddRows = false;

            //dgSite.AllowUserToDeleteRows = false; // 禁止删除行

            //RDeviceBindingSource.DataSource = dtA;
            //dgSite.DataSource = RDeviceBindingSource;

            //dgSite.Columns["id"].HeaderText = "ID";
            //dgSite.Columns["factory_station_id"].HeaderText = "站点ID";
            //dgSite.Columns["fname"].HeaderText = "企业或园区名称";
            //dgSite.Columns["type_name"].HeaderText = "资源类型";
            //dgSite.Columns["parent_factory_station_id"].HeaderText = "上级园区ID";
            //dgSite.Columns["custom_no"].HeaderText = "户号";
            //dgSite.AutoResizeColumns();

            //dgSite.CellContentClick += dgSite_CellContentClick;


            //if (!dgDevice.Columns.Contains("IsSelected"))
            //{
            //    // 创建一个DataGridViewCheckBoxColumn
            //    DataGridViewCheckBoxColumn checkBoxColumn2 = new DataGridViewCheckBoxColumn();
            //    checkBoxColumn2.HeaderText = "选中";
            //    checkBoxColumn2.Name = "IsSelected";
            //    checkBoxColumn2.DataPropertyName = "IsSelected";
            //    // 将勾选列添加到DataGridView
            //    dgDevice.Columns.Add(checkBoxColumn2);
            //}

            //// 设置不允许新增行
            //dgDevice.AllowUserToAddRows = false;

            //dgDevice.AllowUserToDeleteRows = false; // 禁止删除行

            //dgDevice.ContextMenuStrip = contextMenuStrip1;
        }

        private async void dgSite_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //// 检查点击的是否是IsSelected列
            //if (e.RowIndex >= 0)
            //{
            //    if (e.ColumnIndex == dgSite.Columns["IsSelected"].Index)
            //    {
            //        for (int i = 0; i < dgSite.Rows.Count; i++)
            //        {
            //            if (i != e.RowIndex)
            //            {
            //                // 取消其他行IsSelected列的勾选
            //                dgSite.Rows[i].Cells["IsSelected"].Value = false;
            //            }
            //        }
            //        //var dr = SiteBindingSource.Current as DataRowView;
            //        DataRowView drv = RDeviceBindingSource[e.RowIndex] as DataRowView;
            //        if (drv == null)
            //        {
            //            return;
            //        }

            //        var dtA = await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.soureConnectionString, $@"SELECT ID,CLASSNAME,`NAME`,PATHID from dev_powersystemresource where PATHID like '%\\\\{drv["factory_station_id"]}%' AND CLASSNAME = 'Bay' order by PATHID;");
            //        if (dtA.Rows.Count == 0)
            //        {
            //            MessageBox.Show("没有查询到相关数据");
            //            return;
            //        }
            //        // 为DataTable添加对应的列
            //        dtA.Columns.Add("IsSelected", typeof(bool));
            //        dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

            //        DeviceBindingSource.DataSource = dtA;
            //        dgDevice.DataSource = DeviceBindingSource;

            //        dgDevice.Columns["ID"].HeaderText = "ID";
            //        dgDevice.Columns["CLASSNAME"].HeaderText = "类型";
            //        dgDevice.Columns["NAME"].HeaderText = "名称";
            //        dgDevice.Columns["PATHID"].HeaderText = "路径";
            //        dgDevice.AutoResizeColumns();
            //        lbCount.Text = dtA.Rows.Count.ToString();
            //    }
            //}

        }


        private void txtEndDate_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void tsmAllSelect_Click(object sender, EventArgs e)
        {
            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA != null && dtA.Rows.Count > 0)
            {
                //for (int i = 0; i < dgDevice.Rows.Count; i++)
                //{
                //    // 取消其他行IsSelected列的勾选
                //    dgDevice.Rows[i].Cells["IsSelected"].Value = true;
                //}

                foreach (var dr in dtA.AsEnumerable())
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    dr["IsSelected"] = true;
                    dr.EndEdit();
                }
                dgDevice.EndEdit();

            }
        }

        private void tsmAllCancel_Click(object sender, EventArgs e)
        {
            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA != null && dtA.Rows.Count > 0)
            {
                //for (int i = 0; i < dgDevice.Rows.Count; i++)
                //{
                //    // 取消其他行IsSelected列的勾选
                //    dgDevice.Rows[i].Cells["IsSelected"].Value = true;
                //}

                foreach (var dr in dtA.AsEnumerable())
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    dr["IsSelected"] = false;
                    dr.EndEdit();
                }
                dgDevice.EndEdit();

            }
        }

    }
}
